/** 
	插件名称  :  表格插件
	插件功能  :  响应式，支持拖拽调整宽度
	参数      :
				hasHeader : true,
				header : [],
				data : null,
				paginator : true,
				miniPage : true,
				oper : [],
				operStyle:true,
			 	operLayout:true,
				url : "",
				paramObj : new Object(),
				currentPage : 1,
				pageSize : 10,
				isLoad : true,
				allowCheckBox:true,
				maskObj : '',
				isAsync : true,
				dbClick : null,
				hasBorder : true,
				server : null,
				gridCss : "",   um-grid-style
				hideSearch : false,
				hideSort : false,
				cbf : function(){},
				dataKey : "",
				autoHeight:false,
				dbThLine : false,
				showTip : new Object(),
				dbIndex : 0,
				tableWidth : "",
				wholly : false,
				showCount : false,
				cacheSearch : false,
				searchInp : el_inp,
				searchKey : [],
				hasIndex : false,
				originShowCount : 9
*/

define([index_web_app_name+'js/plugin/tip/tip.js'],function (tip){

	return {
		render : function (el ,opt){
			var self = this;

			var default_opt =   {
									hasHeader : true,
									header : [],
									data : null,
									paginator : true,
									oper : [],
									url : "",
									paramObj : new Object(),
									currentPage : 1,
									pageSize : 50,
									isLoad : true,
									allowCheckBox:true,
									maskObj : '',
									isAsync : true,
									dbClick : null,
									hasBorder : true,
									hideSearch : false,
									hideSort : false,
									dataKey : "",
									autoHeight:false,
									dbThLine:false,
									dbIndex:0,
									checkType:"checkbox",
									minHeight:"270px",
									hasIndex:false,
									originShowCount:9
								};

			var opt = $.extend(default_opt ,opt);

			el.data("opt" ,opt);

			var header = opt.header;
			var data = opt.data;
			var oper = opt.oper;
			var url = opt.url;
			var buffer = [];
			var searchBuffer = [];

			if (opt.maskObj == "")
			{
				opt.maskObj = el;
			}

			$.ajax({
				type: "GET",
				url: "js/plugin/grid/grid.html",
				success :function(data)
				{
					var gridEl = $(data);
					var thWidth;
					el.empty();

					// 是否显示分页信息
					if (!opt.paginator)
					{
						gridEl.addClass("no-page")
						if (opt.showCount)
						{
							gridEl.find("[class=um-grid-pager]").find("div").eq(0).remove();
							gridEl.find("[class=um-grid-pager]").find("div").eq(0).remove();
							gridEl.find("[class*=um-grid-pager-info-outer]").children().html('共计 <span data-id="total_record_count" style="font-weight:bold"></span> 条数据');
						}
						else
						{
							gridEl.find("div[class=um-grid-pager-outer]").remove();
							gridEl.find("div[class*=um-grid-table-outer]").css("bottom" ,0);
							gridEl.css("border-bottom" ,"1px solid #ddd");
						}
					}

					if (!opt.hasHeader)
						gridEl.find("tr[class=um-grid-head-tr]").css("opacity" ,"0");

					// 是否有边框
					if (!opt.hasBorder)
					{
						gridEl.css("border" ,"none");
						gridEl.find("tr[class=um-grid-head-tr]").css("border-top" ,"none");
						gridEl.addClass("no-border")
						el.css("height",opt.minHeight)
						gridEl.css("height",opt.minHeight)
					}

					if (opt.dbThLine)
					{
						gridEl.addClass("um-grid-dbline");
					}

					var gridWidth = el.width();

					opt.gridCss && gridEl.addClass(opt.gridCss);

					el.append(gridEl);

					if (!opt.autoHeight){
						gridEl.find('[data-id=um-grid-table-div]').slimscroll({
							height: (el.height() - 36) + "px",
							allowPageScroll: false
						});
					}

					if (opt.tableWidth)
					{
						gridEl.css("padding-bottom" ,"35px");
						gridEl.find("[data-type=tabel-fix-width]").css("width" ,opt.tableWidth);
						gridEl.find("[class*=um-grid-table-outer]").css("bottom" ,"0");
						gridWidth = gridEl.find("[data-type=tabel-fix-width]").width();
						gridEl.css("height" ,(parseInt(gridEl.css("height"))  - 30) + "px")
						el.find(".um-grid-pager-outer").css("bottom" ,"-30px")
					}
					else
					{
						gridEl.find("[data-type=tabel-fix-width-outer]").attr("style" ,"overflow-x:hidden;overflow-y:hidden")
					}
					
					if (opt.miniPage)
					{
						opt.originShowCount = 3
						el.find(".um-grid-pager-info").hide()
						el.find("[data-type=page-sel]").hide()
					}

					gridEl.data("width" ,gridWidth);

					var elWidthWithOutCheckBox = gridWidth;

					// 渲染表头
					// 是否允许全选
					if (opt.allowCheckBox)
					{
						var tmp_opacity = (opt.checkType != "radio"?1:"0")
						elWidthWithOutCheckBox = gridWidth-30;
						buffer.push('<td style="width:29px;opacity:'+tmp_opacity+'" data-id="chk"><div style="width:26px"><div class="checkbox"><label class="i-checks"><input type="checkbox" data-id="check_all"><i></i></label></div></div></td>');
					}

					if (opt.hasIndex)
					{
						elWidthWithOutCheckBox = elWidthWithOutCheckBox - 50
						buffer.push('<td style="width:60px;"><div style="width:57px">序号</div></td>');
					}

					if (opt.operWidth)
					{
						elWidthWithOutCheckBox = elWidthWithOutCheckBox - parseInt(opt.operWidth);
					}

					var widthCount = 100
					var withOutWidthCount = 0
					for (var i=0;i<header.length;i++){
						if (header[i].width)
							widthCount = widthCount - header[i].width
						else
							withOutWidthCount++
					}

					// 未定义表头宽度时的默认值
					var perWidth = widthCount/withOutWidthCount;

					for (var i=0;i<header.length;i++)
					{
						if (header[i].width)
						{
							thWidth = parseInt(header[i].width/100 * elWidthWithOutCheckBox);
						}
						else
						{
							thWidth = parseInt(perWidth/100 * elWidthWithOutCheckBox);
						}
						buffer.push('<td style="width:'+thWidth+'px"><div style="text-align:'+header[i].align+'">'
									+'<span class="custom-down" data-id="sort"></span>'+header[i].text
									+'<span class="resize" data-id="resize_span"></span></div></td>');
					}

					// 是否有操作栏 
					if (opt.oper.length > 0)
					{
						buffer.push('<td data-id="chk_oper"><div></div></td>');
					}

					gridEl.find("[class=um-grid-head]").find("tr").html(buffer.join(""));

					gridEl.find("[class=um-grid-search]").find("tr").html(searchBuffer.join(""));

					gridEl.find("[class=um-grid-search]").find("tr").find("td").not("[data-type=first_td]").each(function (i){
						if (header[i].searchRender)
						{
							header[i].searchRender && header[i].searchRender($(this).find("div") ,header[i].name);
						}
						else
						{
							$(this).find("div").append('<input type="text" class="form-control input-sm" search-data="'+header[i].name+'">');
						}
					});

					el.find("[data-id=pg_sel]").val(opt.pageSize);

					// 渲染数据
					self.renderData(gridEl ,opt);

					// 初始化拖拽事件
					//self.initDrag(gridEl ,opt);
					var el_search_outer = gridEl.find("[class=um-grid-search-outer]");
					var el_table_outer = gridEl.find("[class*=um-grid-table-outer]");

					// 重设查询按钮的位置
					if (!opt.allowCheckBox)
					{
						gridEl.find("[data-type=table_search_i]").css("left" ,"7px");
					}

					// 全选事件
					if (opt.allowCheckBox)
					{
						gridEl.find("[data-id=check_all]").click(function (){
							if ($(this)[0].checked)
							{
								gridEl.find("input[data-id=check_inp]").prop("checked" ,"checked");
							}
							else
							{
								gridEl.find("input[data-id=check_inp]").removeAttr("checked");
							}
						});
					}

					// 分页数change事件
					el.find("[data-id=pg_sel]").select2({
			    		width : "100%"
			    	});

			    	// 排序事件
			    	if(!opt.hideSort){
				    	el.find("[class=um-grid-head-tr]").find("td").not("[data-id=chk]").not("[data-type=oper_td]").each(function (i){
				    		var sortKey;
				    		var sortType;
				    		var sortBy;
				    		$(this).click(function (e){
				    			if ($(e.target).parent().attr("data-id") == "chk_oper")
				    			{
				    				return false;
				    			}
				    			sortKey = header[i].name;
				    			sortBy = (header[i].sortBy ? header[i].sortBy : "");
				    			if ($(this).data("sortType") == "minmax")
				    			{
				    				sortType = "maxmin";
				    			}
				    			else
				    			{
				    				sortType = "minmax";
				    			}
				    			$(this).data("sortType" ,sortType);
				    			if (header[i].sortKey)
				    			{
				    				sortKey = header[i].sortKey;
				    			}
				    			self.sort(el  ,{sortKey:sortKey ,sortType:sortType ,sortBy:sortBy});
				    		});
				    	});
			    	}
			    	
			    	el.find("[class*=select2-selection]").css("height" ,"30px");
			    	el.find("[class*=select2-selection__rendered]").css("line-height" ,"30px");
					el.find("[data-id=pg_sel]").change(function (){
						opt.pageSize = $(this).val();
						opt.currentPage = 1;
						el.find("[data-id=current_page_num]").val(1);
						//self.renderData(gridEl ,opt);

						// 当前查询条件
						// var queryObj = gridEl.find("[class*=um-grid-search-tr]").umDataBind("serialize" ,"search-data");
						// opt.paramObj = queryObj;
						self.renderData(el ,opt);

						self.initPager(el ,opt);
					});

					// resize事件
					if (!opt.tableWidth)
					{
						onWindowResize.add(function (){
							var tdWidthArray = gridEl.data("tdWidthArray");
							gridEl.stopTime();
							gridEl.oneTime(500 ,function (){
								var per;
								if (opt.allowCheckBox)
								{
									per = (gridEl.width()-30)/(gridEl.data("width")-30);
								}
								else
								{
									per = (gridEl.width())/(gridEl.data("width"));
								}
								el.find("[class=um-grid-head]").find("table").find("tr").find("td").not("[data-id*=chk]").each(function (i){
									if (tdWidthArray)
									{
										$(this).width(parseInt(tdWidthArray[i] * per));
										$(this).find("div").width(parseInt(tdWidthArray[i] * per));
									}
								});
								self.initTdWidth(gridEl ,opt);
								gridEl.data("width" ,gridEl.width());
							});
						});
					}
					
				}
			});
		},
		renderData : function (el ,opt){
			var self = this;
			if (!opt.paramObj)
			{
				opt.paramObj = new  Object();
			}
			if (opt.paginator)
			{
				// if (opt.paramObj.currentPageNum)
				// 	opt.currentPage = opt.paramObj.currentPageNum
				// else
				// 	opt.paramObj.currentPageNum = opt.currentPage
				opt.paramObj.currentPageNum = opt.currentPage;
				opt.paramObj.pageSize = opt.pageSize;	
				//opt.paramObj.pageSize = opt.pageSize;
			}
			var data = opt.data;
			if (data)
			{
				if (data[0] && data[0].recordCount)
					el.data("recordCount" ,data[0].recordCount)
				inFunc_render(data);
			}
			else
			{
				if(opt && opt.queryBefore)
				{
					var queryBeforeResult = opt.queryBefore(opt.paramObj)
					if(queryBeforeResult)
					{
						opt.paramObj = queryBeforeResult;
					}
				}
				var um_opt = {
								url : opt.url,
								isLoad : opt.isLoad,
								paramObj : opt.paramObj,
								maskObj : opt.maskObj,
								isAsync : opt.isAsync,
								server : opt.server,
								successCallBack : function (data){
									if (data.totalCount)
										el.data("recordCount" ,data.totalCount)
									if (opt.dataKey)
									{
										data = data[opt.dataKey];
									}
									if (data[0] && data[0].recordCount)
										el.data("recordCount" ,data[0].recordCount)
									inFunc_render(data);
								}
							}
				if (opt.type == "get")
					um_ajax_get(um_opt);
				else if (opt.type == "xd")
					xd_ajax_get(um_opt)
				else
					um_ajax_post(um_opt);
				
			}

			function inFunc_render(data)
			{
				self.emptyDivHide(el)
				var header = opt.header;
				var oper = opt.oper;
				var buffer = [];
				var dataObj;
				var tdText;
				el.data("record" ,data);
				if (!data || data.length == 0)
				{
					if (el.find("[data-id=check_all]").size() > 0)
					{
						el.find("[data-id=check_all]")[0].checked = false;
					}
					self.noDatPagerInit(el);
					// 自适应高度
					if (opt.autoHeight)
					{
						self.autoHeight(el ,opt)
					}
					if (opt.url)
						self.emptyDivShow(el ,opt)
					opt.cbf && opt.cbf();
					return false;
				}
				
				// 渲染TR
				self.renderTr(el ,opt ,data ,true);

				if (el.find("[data-id=check_all]").size() > 0)
				{
					el.find("[data-id=check_all]")[0].checked = false;
				}

				// 初始化分页
				if (opt.paginator || opt.showCount)
				{
					// 初始化分页
					self.initPager(el ,opt);
					// 初始化分页点击事件
					self.initPagerEvent(el ,opt);
				}

				if (opt.wholly)
				{
					el.find('[data-id=um-grid-table-div]').find("table").addClass("wholly");
					el.find('[data-id=um-grid-table-div]').find("table").wholly({
			            highlightHorizontal: 'wholly-highlight-horizontal',
			            highlightVertical: 'wholly-highlight-vertical'
			        });
				}
				
				// 渲染实时搜索
				if (opt.cacheSearch)
				{
					self.cacheSearch(el ,opt);
				}

				opt.cbf && opt.cbf();

				if (opt.showTip)
				{
					el.find("tr").not("[class=um-grid-head-tr]").not("[class=um-grid-search-tr]").each(function (){
						var trEl = $(this);
						trEl.find("td").not("[data-id=chk]").eq(0).addClass("tip");
						trEl.find("td").not("[data-id=chk]").eq(0).click(function (){
							$("body").find("tr[class=active]").removeClass("active");
							trEl.addClass("active");
							opt.showTip.render && opt.showTip.render(trEl.data("data"));
							return false;
						});
					});

					// 绑定页面点击事件
					$("body").on("click.grid" ,function (e){
						if ($(e.target).attr("class") == "umDialog-right-content"
								|| $(e.target).closest("[class=umDialog-right-content]").size() > 0
								|| $(e.target).closest("[class=um_mask]").size() > 0)
						{
							return false;
						}
						else if ($(e.target).closest("div.checkbox").size() > 0)
						{
						}
						else
						{
							el.find("tr").not("[class=um-grid-head-tr]").not("[class=um-grid-search-tr]").removeClass("active");
							g_dialog.rightDialogHide();
							return false;
						}
					});

					// 绑定键盘上移下移事件
					$("body").on("keypress.grid" ,function (event){
						var keycode = (event.keyCode ? event.keyCode : event.which);
						var currentTR = el.find("tr[class=active]");
						// 上移
					    if(keycode == '40')
					    {  
					        currentTR.next().find("td").not("[data-id=chk]").eq(0).click();
					        //return false;
					    }
					    // 下移
					    if (keycode == '38')
					    {
					    	currentTR.prev().find("td").not("[data-id=chk]").eq(0).click();
					    	//return false;
					    }
					})
				}
			}
		},
		isOutTr:function(data){
			return false;
		},
		emptyDivShow:function (el ,opt){
			if (el.hasClass("um-grid"))
			{
				el.css("height" ,opt.minHeight)
				el.parent().css("height" ,opt.minHeight)
			}
			else
			{
				el.css("height" ,opt.minHeight)
				el.children().css("height" ,opt.minHeight)
			}
			var el_table_outer = el.find("[class*=um-grid-table-outer]");
			var el_empty_div = $('<div class="um-grid-empty"></div>').appendTo(el)
			if (el_table_outer.hasClass("um-grid-search-outer-expand"))
				el.find("[class*=um-grid-empty]").css("z-index" ,"1999")
			else
				el.find("[class*=um-grid-empty]").css("z-index" ,"2000")
			el.find("[data-type=um-grid-pager-outer]").hide()
		},
		emptyDivHide:function (el){
			el.find("[class*=um-grid-empty]").remove()
		},
		emptyDivRemove:function (){
		},
		interceptData:function(data){
		},
		renderTr : function (el ,opt ,data ,emptyFlag){
			var self = this;
			var header = opt.header;
			var oper = opt.oper;
			var buffer = [];
			var dataObj;
			var tdText;
			var titleText;
			if (emptyFlag)
			{
				el.find("[data-id=um-grid-table-div]").find("table").html("");
			}
			self.interceptData(data);
			for (var i=0;i<data.length;i++)
			{
				if(self.isOutTr(data[i]) == true){
					continue;
				}
				var trObj = $('<tr></tr>')
				//buffer = [];
				//buffer.push("<tr>");
				dataObj = data[i];
				titleText = "";
				// 是否允许全选
				if (opt.allowCheckBox)
				{
					//buffer.push
					trObj.append('<td style="width:29px" data-id="chk"><div style="width:29px"><div class="checkbox"><label class="i-checks"><input type="'
								+opt.checkType+'" name="grid_check_type" data-id="check_inp" '+(data[i].gridChecked?"checked":"")+'><i></i></label></div></div></td>');
				}
				if (opt.hasIndex)
				{
					//buffer.push
					trObj.append('<td style="width:60px"><div style="width:57px">'+parseInt((opt.currentPage-1)*opt.pageSize + (i+1))+'</td>')
				}
				for (var j=0;j<header.length;j++)
				{
					tdText = dataObj[header[j].name];
					titleText = ""
					if (header[j].render)
					{
						tdText = header[j].render(tdText ,dataObj);
					}
					if (header[j].tip)
					{
						if (header[j].tipInfo)
						{
							titleText = 'title="' + dataObj[header[j].tipInfo] +'"' +"'";
						}
						else
						{
							titleText = 'title="' + dataObj[header[j].name] +'"' +"'";
						}
					}
					else if (tdText == null || tdText === "")
					{
						tdText = header[j].emptyInfo || ""
					}
					else if (!header[j].render)
					{
						titleText = 'title="' + dataObj[header[j].name] +'"' +"'";
					}
					//buffer.push
					var __tmp = $('<td><div class="__td_div_content" style="text-align:'+header[j].align+';font-weight:'+header[j].bold+'" '+titleText+'>'+tdText+'</div></td>')
					if (header[j].renderType == "text")
						__tmp.find(".__td_div_content").text(tdText)
					trObj.append(__tmp);
				}
				// 渲染操作栏
				if (oper && oper.length > 0)
				{
					var buffer = []
					buffer.push('<td data-type="oper_td" style="text-align:center">');
					for (var j=0;j<oper.length;j++)
					{
						oper[j].render && (oper[j].icon = oper[j].render(data[i]));

						var operTmp = oper[j];

						if (oper[j].customRender)
						{
							operTmp = oper[j].customRender(data[i]);
						}
						
						if (!oper[j].isShow || oper[j].isShow(data[i]))
						{
							if (opt.operStyle)
							{
								if (opt.operLayout)
								{
									buffer.push('<a data-type="aclick" href="javascript:void(0);" style="color:#000;float:left;width:'+operTmp.width+'"><i class="'+(operTmp.style?operTmp.style:opt.operStyle)+'" title="'+operTmp.text+'">'+operTmp.text+'</i></a>');
								}
								else
								{
									buffer.push('<a data-type="aclick" href="javascript:void(0);" style="color:#000;margin:0 3px"><i class="'+(operTmp.style?operTmp.style:opt.operStyle)+'" title="'+operTmp.text+'">'+operTmp.text+'</i></a>');
								}
							}
							else
							{
								buffer.push('<a data-type="aclick" href="javascript:void(0);" style="color:#000;margin:0 3px">'+operTmp.text+'</a>');
							}
						}
						else
						{
							buffer.push('<a data-type="aclick" style="display: inline-block; width: 19px;height: 1px;margin: 0 3px;opacity:0"></a>');
						}
					}
					buffer.push("</td>");
					trObj.append(buffer.join(""))
				}

				//buffer.push("</tr>");

				//var trObj = $(buffer.join(""));

				el.find("[data-id=um-grid-table-div]").find("table").append(trObj);

				trObj.data("data" ,data[i]);

				// 绑定选中事件
				trObj.find("[data-id=check_inp]").click(function (){
					var trData = $(this).closest("tr").data("data");
					$(this).is(":checked")?(trData.gridChecked=true):(trData.gridChecked=false);
				});

				// 绑定操作栏事件
				trObj.find("[data-type=oper_td]").each(function (){
					$(this).find("[data-type=aclick]").each(function (i){
						$(this).click(function (){
							oper[i].aclick($(this).closest('tr').data("data") ,$(this).closest('tr'));
							return false;
						});
					});
				});
			}
			// 给td绑定双击事件
			if (opt.tdDbClick)
			{
				self.tdDbClick(el ,opt);
			}
			// 给td绑定单击事件
			if (opt.tdClick)
			{
				self.tdClick(el ,opt);
			}
			// 双击事件
			if (opt.dbClick)
			{
				el.find("tr").not("[class=um-grid-head-tr]").not("[class=um-grid-search-tr]").each(function (){
					var trEl = $(this);
					//trEl.find("td").not("[data-id=chk]").eq(opt.dbIndex).attr("title" ,"点击查看详情");
					trEl.find("td").not("[data-id=chk]").eq(opt.dbIndex).addClass("tip");
					trEl.find("td").not("[data-id=chk]").eq(opt.dbIndex).click(function (){
						opt.dbClick(trEl.data("data"));
						return false;
					});
				});
			}
			// 初始化单元格宽度
			self.initTdWidth(el ,opt);

			// 自适应高度
			if (opt.autoHeight)
				self.autoHeight(el ,opt)

			el.find("[data-type=um-grid-pager-outer]").show()
		},
		addData : function (el ,data){
			var opt = el.data("opt");
			var header = opt.header;
			var oper = opt.oper;
			var buffer = [];
			var dataObj;
			var tdText;
			// 渲染TR
			this.renderTr(el ,opt ,data);
			if (opt.wholly)
			{
				el.find('[data-id=um-grid-table-div]').find("table").unbind("mouseenter");
				el.find('[data-id=um-grid-table-div]').find("table").unbind("mouseleave");
				el.find('[data-id=um-grid-table-div]').find("table").wholly({
			            highlightHorizontal: 'wholly-highlight-horizontal',
			            highlightVertical: 'wholly-highlight-vertical'
			    });
			}
			if (opt.showTip)
			{
				el.find("tr").not("[class=um-grid-head-tr]").not("[class=um-grid-search-tr]").each(function (){
					var trEl = $(this);
					trEl.find("td").not("[data-id=chk]").eq(0).addClass("tip");
					trEl.find("td").not("[data-id=chk]").eq(0).click(function (){
						$("body").find("tr[class=active]").removeClass("active");
						trEl.addClass("active");
						opt.showTip.render && opt.showTip.render(trEl.data("data"));
						return false;
					});
				});
			}
			el.find("[data-id=total_record_count]").text(data[0]?data[0].recordCount:0);
			el.find("[data-id=current_page_record_count]").text(data.length);
			this.emptyDivHide(el)
		},
		updateData : function (el ,option){
			var opt = el.data("opt");
			var header = opt.header;
			var trObj = option.trObj;
			var newData = option.data;
			trObj.data("data" ,newData);
			trObj.find("td").not("[data-id=chk]").not("[data-type=oper_td]").each(function (i){
				if (header[i].render)
				{
					$(this).find("div").html(header[i].render(newData[header[i].name]));
				}
				else
				{
					$(this).find("div").html(newData[header[i].name]);
				}
				
			});
		},
		cacheSearch : function (el ,opt){
			var self = this;
			el.data("opt" ,opt);
			var el_search_inp = opt.searchInp;
			var searchKeyArray = opt.searchKey;
			var delayFlag = true;
			var data = el.data("record");
			var cacheMap = new HashMap();
			var cacheStrArray = [];
			var inpVal;
			var dataStr = [];
			var dataIndex;
			var newData = [];
			for (var i = data.length - 1; i >= 0; i--){
				dataStr = [];
				for (var j = 0; j < searchKeyArray.length; j++) {
					dataStr.push(data[i][searchKeyArray[j]]);
				}
				cacheMap.put(dataStr.join(",") ,i);
				cacheStrArray.push(dataStr.join(","));
			}
			el_search_inp.on("keyup" ,function (){
				if (delayFlag)
				{
					el_search_inp.oneTime(500 ,function (){
						newData = [];
						inpVal = el_search_inp.val();
						for (var i = cacheStrArray.length - 1; i >= 0; i--) {
							dataIndex = cacheStrArray[i].toLowerCase().indexOf(inpVal.trim().toLowerCase());
							if (dataIndex > -1)
							{
								newData.push(data[cacheMap.get(cacheStrArray[i])]);
							}
						}
						delayFlag = true;
						self.removeData(el ,{t:1});
						self.addData(el ,newData);
					});
				}
				delayFlag = false;
			})
		},
		refresh : function (el ,option){
			var opt = el.data("opt");
			var queryObj = {}

			if (option && option.resetPage)
			{
				option.currentPageNum = 1
				opt.currentPage = 1
				el.find("[data-num]").removeClass("active")
				el.find("[data-id=current_page_num]").val(1);
			}
			if (option && option.queryBefore)
			{
				var queryBeforeResult = option.queryBefore(queryObj)
				if (queryBeforeResult)
					queryObj = queryBeforeResult;
			}
			opt.paramObj = $.extend(queryObj ,opt.paramObj)
			if (option && option.paramObj)
				opt.paramObj = $.extend(opt.paramObj ,option.paramObj)

			this.renderData(el ,opt);
		},
		removeData : function(el ,option){
			// 不传参数时，删除checkbox选中的
			if (!option)
			{
				el.find("[data-id=check_inp]").each(function (){
					$(this).is(":checked") && ($(this).closest("tr").remove());
				});
				el.find("[data-id=check_all]").attr("checked" ,false);
			}
			else
			{
				el.find("[class=um-grid-table]").find("tr").remove();
				el.find("[data-id=check_all]").attr("checked" ,false);
			}
		},
		getData : function (el ,option){
			var dataList = [];
			el.find("[data-id=um-grid-table-div]").find("table").find("tr").each(function (i){
				var flag = true;
				if (option && option.chk)
				{
					flag = $(this).find("[data-id=check_inp]").is(":checked");
				}
				flag && dataList.push($(this).data("data"));
			});
			return dataList;
		},
		getTrObj : function (el ,option){
			if (option && (option.index || option.index == 0))
			{
				return el.find("[data-id=um-grid-table-div]").find("table").find("tr").eq(option.index);
			}
			else
			{
				return el.find("[data-id=um-grid-table-div]").find("table").find("tr");
			}
		},
		getIdArray : function (el ,option)
		{
			var idArray = [];
			el.find("[data-id=um-grid-table-div]").find("table").find("tr").each(function (i){
				var flag = true;
				if (option && option.chk)
				{
					flag = $(this).find("[data-id=check_inp]").is(":checked")
				}
				flag && idArray.push($(this).data("data")[option.attr]);
			});
			return idArray;
		},
		moveUp : function (trObj){
			var a = trObj;
			var b = trObj.prev();
			a.insertBefore(b);
		},
		moveDown : function (trObj){
			var a = trObj;
			var b = trObj.next();
		    a.insertAfter(b);
		},
		tdDbClick : function (el ,opt){
			var header = opt.header;
			el.find("[data-id=um-grid-table-div]").find("table").find("tr").each(function (i){
				var el_td = $(this);
				$(this).find("td").not("[data-id=chk]").not("[data-type=oper_td]").each(function (j){
					if (header[j].dbclick)
					{
						$(this).dblclick(function (){
							if ($(this).find("input").size() > 0)
							{
								return false;
							}
							var tmpStr = $(this).find("div").html();
							var el_td_div = $(this).find("div");
							el_td_div.html('<input style="width:95%"/>');
							el_td_div.find("input").focus().val(tmpStr);
							el_td_div.find("input").blur(function (){
								el_td_div.html($(this).val());
								var el_tr_data = el_td.closest("tr").data("data");
								el_tr_data[header[j].name] = $(this).val();
								header[j].tdBlur && header[j].tdBlur(el_td.closest("tr"));
							});
						});
					}
				});
			});
		},
		tdClick : function (el ,opt){
			var header = opt.header;
			el.find("[data-id=um-grid-table-div]").find("table").find("tr").each(function (i){
				$(this).find("td").not("[data-id=chk]").not("[data-type=oper_td]").each(function (j){
					var el_td = $(this);
					if (header[j].click)
					{
						if (el_td.find("i").size() > 0)
						{
							el_td.find("i").click(function (){
								var el_tr_data = el_td.closest("tr").data("data");
								header[j].click(el_tr_data);
							});
						}
						else
						{
							el_td.click(function (){
								var el_tr_data = el_td.closest("tr").data("data");
								header[j].click(el_tr_data);
							});
						}
						
					}
				});
			});
		},
		initPager : function (el ,opt){
			var self = this;

			var recordCount = el.data("recordCount")

			var data = el.data("record");

			if (!data || data.length == 0)
			{
				return false;
			}

			var currentPage = el.find("[data-id=current_page_num]").val();

			el.data("currentPage" ,currentPage);

			el.find("[data-id=total_record_count]").text(recordCount);

			var el_first_page = el.find("[data-id=first_page]");
			var el_prev_page = el.find("[data-id=prev_page]");
			var el_next_page = el.find("[data-id=next_page]");
			var el_last_page = el.find("[data-id=last_page]");
			var el_page_num_div = el.find("[data-type=page-num-div]")

			var pageObj = self.getPageList(Math.ceil(recordCount/opt.pageSize) ,currentPage ,opt.originShowCount)
			
			el_page_num_div.empty()
			var pageList = pageObj.pageList
			for (var i = 0; i < pageList.length; i++) {
				el_page_num_div.append('<span class="__num" data-num="'+pageList[i]+'">'+pageList[i]+'</span>')
			}
			el_page_num_div.find("[data-num="+currentPage+"]").addClass("active")
			
			if (pageObj.prev)
				el_prev_page.show()
			else
				el_prev_page.hide()
			if (pageObj.next)
				el_next_page.show()
			else
				el_next_page.hide()
		},
		initPagerEvent : function (el ,opt){
			var self = this;
			var data = el.data("record");
			var recordCount = el.data("recordCount")
			opt.isLoad = true;

			if (!data || data.length == 0)
			{
				return false;
			}

			var el_first_page = el.find("[data-id=first_page]");
			var el_prev_page = el.find("[data-id=prev_page]");
			var el_next_page = el.find("[data-id=next_page]");
			var el_last_page = el.find("[data-id=last_page]");
			var el_page_num_div = el.find("[data-type=page-num-div]")

			el_first_page.off("click");
			el_prev_page.off("click");
			el_next_page.off("click");
			el_last_page.off("click");
			
			// if (!el_prev_page.hasClass("forbid"))
			// {
				el_prev_page.click(function (){
					opt.currentPage = parseInt(el.data("currentPage")) - 1;
					el.find("[data-id=current_page_num]").val(opt.currentPage);
					self.renderData(el ,opt);
					//self.initPager(el ,opt);
				});
			// }

			// if (!el_next_page.hasClass("forbid"))
			// {
				el_next_page.click(function (){
					opt.currentPage = parseInt(el.data("currentPage")) + 1;
					el.find("[data-id=current_page_num]").val(opt.currentPage);
					self.renderData(el ,opt);
					//self.initPager(el ,opt);
				});
			// }

			el_page_num_div.children().click(function (){
				opt.currentPage = $(this).text()
				el.find("[data-id=current_page_num]").val(opt.currentPage);
				self.renderData(el ,opt);
			})
		},
		noDatPagerInit : function (el){
			el.find("[data-id=first_page]").off("click").removeClass("forbid").addClass("forbid");
			el.find("[data-id=prev_page]").off("click").removeClass("forbid").addClass("forbid");
			el.find("[data-id=next_page]").off("click").removeClass("forbid").addClass("forbid");
			el.find("[data-id=last_page]").off("click").removeClass("forbid").addClass("forbid");

			el.find("[data-id=current_page_record_count]").text(0);
			el.find("[data-id=total_record_count]").text(0);

			el.find("[data-id=um-grid-table-div]").find("table").html("");
		},
		initTdWidth : function (el ,opt)
		{
			var header = opt.header;
			var tdWidthArray = [];
			var thTmp = el.find("[class=um-grid-head]").find("table").find("tr").find("td").not("[data-id*=chk]");
			var grid_table = el.find("[data-id=um-grid-table-div]").find("table");
			thTmp.each(function (i){
				tdWidthArray.push(parseInt(thTmp.eq(i).css("width")));
			});

			el.data("tdWidthArray" ,tdWidthArray);
			var chk_width = el.find("[class=um-grid-head]").find("[data-id*=chk]").width()
			grid_table.find("tr").not("[class*=expand-tr]").each(function (){
				$(this).find("td[data-id=chk]").css("width" ,chk_width + "px");
				$(this).find("td[data-id=chk]").find("div").css("width" ,(chk_width-3) + "px");
			});

			for (var i=0;i<header.length;i++)
			{
				var width = tdWidthArray[i];
				grid_table.find("tr").not("[class*=expand-tr]").each(function (){
					$(this).find("td").not("[data-id=chk]").eq(i).css("width" ,width + "px");
					$(this).find("td").not("[data-id=chk]").eq(i).find("div").css("width" ,(width-3) + "px");
				});
			}
		},
		initDrag : function (el ,opt){
			var self = this;
			//鼠标离控件左上角的相对位置
			var _x;
			var _y;

			var _left;

			var leftColumn;
			var rightColumn;

			var leftColumnStartWidth;
			var rightColumnStartWidth;

			var thTmp;
			var thAttr;

			el.find("[data-id=resize_span]").mousedown(function (e){
				e.preventDefault();
				var left = getTdWidthFromLeft($(e.target).closest("td"));
				el.find("[data-id=um-grid-resize-mark]").css("left" ,left + "px");
				el.find("[data-id=um-grid-resize-mark]").show();
				_x = e.pageX;
				_y = e.pageY;
				_left = parseInt(el.find("[data-id=um-grid-resize-mark]").css("left"));
				leftColumn = $(this).closest('td');
				rightColumn = $(this).closest('td').next();

				leftColumnStartWidth = leftColumn.width();
				rightColumnStartWidth = rightColumn.width();

				$(document).on('mousemove.rc' ,function (e){
					difference = e.pageX - _x;
					leftColumn.width(leftColumnStartWidth + difference);
					leftColumn.find("div").width(leftColumnStartWidth + difference);
					rightColumn.width(rightColumnStartWidth - difference);
					rightColumn.find("div").width(rightColumnStartWidth - difference);

				});

				$(document).one('mouseup' ,function (e){
					$(document).off('mousemove.rc');
					el.find("[data-id=um-grid-resize-mark]").hide();
					self.initTdWidth(el ,opt);
				});
			});

			// $("body").mouseup(function (){
			// 	el.find("[data-id=um-grid-resize-mark]").hide();
			// });

			function getTdWidthFromLeft(elTd){	
				var el = elTd;
				var elWidth = el.width();
				while (el.width() != null)
				{
					el = el.prev();
					elWidth = elWidth + (el.width() == null ? 0 : el.width());
				}
				return elWidth;
			}
		},
		autoHeight : function (el ,opt){
			// 带showCount才会有查找无数据的背景图片
			var extendHeight = opt.showCount?100:50
			var el_table = el.find('[data-id=um-grid-table-div]').find("table")
			el.find("[class=slimScrollBar]").css("opacity" ,"0");
			if (el.hasClass("um-grid"))
			{
				el.height(el_table.height() + extendHeight)
				el.parent().height(el.height())
			}
			else
			{
				el.height(el_table.height() + extendHeight)
				el.children().height(el.height())
			}
		},
		resize : function (el){
			var opt = el.data("opt");

			var header = opt.header;

			var thWidth;

			var widthCount = 100
			for (var i=0;i<header.length;i++){
				if (header[i].width)
					widthCount = widthCount - header[i].width

			}
			// 未定义表头宽度时的默认值
			var perWidth = widthCount/header.length;

			var elWidthWithOutCheckBox = el.width();

			if (opt.allowCheckBox)
			{
				elWidthWithOutCheckBox = el.width()-30;
			}

			if (opt.operWidth)
			{
				elWidthWithOutCheckBox = elWidthWithOutCheckBox - parseInt(opt.operWidth);
			}

			for (var i=0;i<header.length;i++)
			{
				if (header[i].width)
				{
					thWidth = parseInt(header[i].width/100 * elWidthWithOutCheckBox);
				}
				else
				{
					thWidth = parseInt(perWidth/100 * elWidthWithOutCheckBox);
				}
				el.find("[class*=um-grid-head-tr]").find("td").not("[data-id=chk]").eq(i).css("width" ,thWidth + "px");
				el.find("[class*=um-grid-head-tr]").find("td").not("[data-id=chk]").eq(i).find("div").css("width" ,(thWidth-3) + "px");
			}

			this.initTdWidth(el ,opt);
		},
		sort : function (el ,opt){
			var sortType = opt.sortType;
			var sortBy = opt.sortBy;
			// 从小到大
			if (sortType == "minmax")
			{
				var min = -1;
				var max = 1;
			}
			// 从大到小
			else if (sortType == "maxmin")
			{
				var min = 1;
				var max = -1;
			}
			var by = function (name){
				return function (o ,p){
					var a,b;
					if (typeof o === "object" && typeof p === "object" && o && p)
					{
						a = o[name];
						b = p[name];
						if (sortBy == "int")
						{
							a = parseInt(a);
							b = parseInt(b);
						}
						if (a === b)
						{
							return 0;
						}
						if (typeof a === typeof b)
						{
							return a < b ? min : max;
						}
						return typeof a < typeof b ? min : max;
					}
					else
					{
						throw("error");
					}
				}
			}
			var dataArray = this.getData(el ,{chk:false});

			var sortedDataArray = dataArray.sort(by(opt.sortKey));
			this.removeData(el ,{});
			this.addData(el ,sortedDataArray);
		},
		getPageList : function (allcount ,currentIndex ,originShowCount){
			originShowCount = originShowCount || 9
			currentIndex = parseInt(currentIndex)
			var resultArray = [];
			if(allcount<0)throw "异常的总页码";
			if(originShowCount<1)throw "异常的可显示页码";
			if(currentIndex>allcount && allcount != 0 || currentIndex < 1)throw "异常的当前页码";
			if(allcount>=originShowCount){
				var showcount;
				showcount = originShowCount;
				var beforeOffset = Math.floor(showcount /2) ;
				if(currentIndex- beforeOffset + showcount -1 > allcount){
					beforeOffset = beforeOffset + currentIndex- beforeOffset + showcount -1 - allcount ;
				}
				if(currentIndex - beforeOffset >0){
					for(var i=currentIndex - beforeOffset;i<=currentIndex - beforeOffset + showcount -1;i++ ){
						resultArray.push(i);
					}
				}else {
					for(var i =1 ;i<=showcount ; i++){
						resultArray.push(i);
					}
				}
			}else {
				for(var i =1 ;i<=allcount ; i++){
					resultArray.push(i);
				}
			}
			if(resultArray.length == 0)resultArray.push(1);
			var prev = currentIndex == 1 ? false : true;
			var next = currentIndex == allcount ? false : true;
			
			var resultObj = {
				prev : prev ,
				next : next ,
				pageList : resultArray
			}
			return resultObj
		}
	}

});